<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="护理日期" prop="nursingDateTime">
        <el-date-picker clearable
                        v-model="queryParams.nursingDateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择护理日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="生命体征记录" prop="vitals" label-width="140px">
        <el-input
            v-model="queryParams.vitals"
            placeholder="请输入生命体征记录"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者情况记录" prop="patientConditionRecord" label-width="100px">
        <el-input
            v-model="queryParams.patientConditionRecord"
            placeholder="请输入患者情况记录"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="患者姓名" prop="patientName" >
        <el-select
            v-model="queryParams.patientName"
            placeholder="请选择患者姓名"
            clearable
            filterable
            @change="handlePatientChange"
        >
          <el-option
              v-for="patient in patientList"
              :key="patient.patientId"
              :label="patient.realName"
              :value="patient.realName"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['nurse:nurserecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['nurse:nurserecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['nurse:nurserecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['nurse:nurserecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="nurserecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="护理日期时间" align="center" prop="nursingDateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.nursingDateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="护理内容" align="center" prop="nursingContent" />
      <el-table-column label="生命体征记录" align="center" prop="vitals" />
      <el-table-column label="患者情况记录" align="center" prop="patientConditionRecord" />
<!--      <el-table-column label="员工id" align="center" prop="nurseId" />-->
      <el-table-column label="护士姓名" align="center" prop="nurseName" />
      <!--      <el-table-column label="患者姓名" align="center" prop="patientName" />-->
      <el-table-column label="患者姓名" align="center" prop="patientName">

        <template #default="scope">
          <el-link type="primary" @click="handleViewPatientRecords(scope.row.patientName)">
            {{ scope.row.patientName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nurse:nurserecord:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nurse:nurserecord:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />



    <!-- 患者护理记录对话框 -->
    <el-dialog :title="`${selectedPatientName} 的护理记录`" v-model="patientRecordsDialogVisible" width="80%">
      <el-table :data="patientRecords">
        <el-table-column label="护理日期时间" align="center" prop="nursingDateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.nursingDateTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="护理内容" align="center" prop="nursingContent" />
        <el-table-column label="生命体征记录" align="center" prop="vitals" />
        <el-table-column label="患者情况记录" align="center" prop="patientConditionRecord" />
        <el-table-column label="护士姓名" align="center" prop="nurseName" />
        <el-table-column label="患者姓名" align="center" prop="patientName" />

      </el-table>
    </el-dialog>

    <!-- 添加或修改患者住院护理记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="nurserecordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="护理日期时间" prop="nursingDateTime">
          <el-date-picker clearable
                          v-model="form.nursingDateTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择护理日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="护理内容">
          <el-select
              v-model="form.nursingContent"
              placeholder="请选择或输入护理内容"
              filterable
              allow-create
              default-first-option
          >
            <el-option label="输液" value="输液" />
            <el-option label="换药" value="换药" />
          </el-select>
        </el-form-item>
        <el-form-item label="生命体征记录" prop="vitals">
          <el-input
              v-model="form.vitals"
              placeholder="体温（℃）/脉搏（次/分）/呼吸（次/分）/血压（mmHg）/血氧饱和度（%）"
          />
          <el-button
              type="text"
              @click="applyVitalsTemplate"
              style="margin-left: 10px;"
          >使用模板</el-button>
        </el-form-item>
        <el-form-item label="患者情况记录" prop="patientConditionRecord">
          <el-select
              v-model="form.patientConditionRecord"
              placeholder="请选择或输入患者情况"
              filterable
              allow-create
              default-first-option
          >
            <el-option label="良好" value="良好" />
            <el-option label="稳定" value="稳定" />
            <el-option label="好转" value="好转" />
            <el-option label="危急" value="危急" />
            <el-option label="观察中" value="观察中" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="患者姓名" prop="patientName">
          <el-select
              v-model="form.patientName"
              placeholder="请选择患者姓名"
              clearable
              filterable
              @change="handlePatientChange"
          >
            <el-option
                v-for="patient in patientList"
                :key="patient.patientId"
                :label="patient.realName"
                :value="patient.realName"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="住院登记表编号" prop="registrationId">-->
<!--          <el-input v-model="form.registrationId" placeholder="请输入住院登记表编号" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nurserecord">
import {
  listNurserecord,
  getNurserecord,
  delNurserecord,
  addNurserecord,
  updateNurserecord,
  listNurserecord2
} from "@/api/nurse/nurserecord";
import {getMEmoployee, listBeinhospital, listjiuzhen} from "@/api/nurse/beinhospital.js";

const {proxy} = getCurrentInstance();

const nurserecordList = ref([]);
const patientList = ref([]); // 患者列表
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const patientRecordsDialogVisible = ref(false); // 控制对话框的显示
const patientRecords = ref([]); // 存储患者的护理记录
const selectedPatientName = ref(""); // 当前选中的患者姓名
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nursingDateTime: null,
    nursingContent: null,
    vitals: null,
    patientConditionRecord: null,
    nurseId: null,
    patientName: null, // 替换为患者姓名
    registrationId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

// function handleViewPatientRecords(patientName) {
//   // 过滤出对应患者的护理记录
//   const filteredRecords = nurserecordList.value.filter(record => record.patientName === patientName);
//
//   // 将过滤后的记录赋值给一个新的变量，用于显示
//   patientRecords.value = filteredRecords;
//
//   // 打开一个对话框显示患者的护理记录
//   patientRecordsDialogVisible.value = true;
// }
function handleViewPatientRecords(patientName) {
  // 过滤出对应患者的护理记录
  const filteredRecords = nurserecordList.value.filter(record => record.patientName === patientName);

  // 获取患者的护理记录，并查询护士姓名
  const patientRecordsWithNurseName = filteredRecords.map(async (record) => {
    if (record.nurseId) {
      try {
        const nurseResponse = await getMEmoployee(record.nurseId);
        record.nurseName = nurseResponse.name || "未知"; // 获取护士姓名
      } catch (error) {
        console.error("查询护士信息失败：", error);
        record.nurseName = "未知";
      }
    }
    return record;
  });

  // 等待所有护士姓名查询完成
  Promise.all(patientRecordsWithNurseName).then((updatedRecords) => {
    patientRecords.value = updatedRecords; // 更新对话框中的护理记录
    selectedPatientName.value = patientName; // 设置当前选中的患者姓名
    patientRecordsDialogVisible.value = true; // 打开对话框
  });
}

function applyVitalsTemplate() {
  form.value.vitals = "36.5℃/72次/分/16次/分/120/80mmHg/98%";
}


// 获取患者列表
function getPatientList() {
  listjiuzhen().then((response) => {
    patientList.value = response || []; // 假设后端返回患者列表
    console.log("患者列表：", patientList.value);
  }).catch(error => {
    console.error("获取患者列表失败：", error);
  });
}


// 查询患者住院护理记录列表
async function getList() {
  loading.value = true;
  try {
    const response = await listNurserecord(queryParams.value); // 获取护理记录列表
    const nursingRecordsWithLatestNurseId = await Promise.all(
        response.rows.map(async (item) => {
          const patient = patientList.value.find((p) => p.patientId === item.patientId);
          if (patient) {
            try {
              const hospitalRecords = await listBeinhospital({ patientId: patient.patientId }); // 查询患者的住院记录
              if (hospitalRecords.rows.length > 0) {
                const latestRecord = hospitalRecords.rows.sort(
                    (a, b) => new Date(b.admissionTime) - new Date(a.admissionTime)
                )[0]; // 找到最新的住院记录
                item.nurseId = latestRecord.nurseId; // 将最新住院记录的护士 ID 赋值给护理记录的护士 ID

                // 查询护士姓名
                if (item.nurseId) {
                  const nurseResponse = await getMEmoployee(item.nurseId);
                  item.nurseName = nurseResponse.name || "未知"; // 获取护士姓名
                }
              }
            } catch (error) {
              console.error("查询住院记录失败：", error);
            }
          }
          return {
            ...item,
            patientName: patient ? patient.realName : "未知", // 替换患者 ID 为患者姓名
            nurseName: item.nurseName || "未知" // 确保护士姓名字段存在
          };
        })
    );
    nurserecordList.value = nursingRecordsWithLatestNurseId; // 更新护理记录列表
    total.value = response.total; // 更新总记录数
  } catch (error) {
    console.error("获取护理记录列表失败：", error);
  } finally {
    loading.value = false; // 关闭加载状态
  }
}
// 患者姓名下拉框变化时
function handlePatientChange(value) {
  const selectedPatient = patientList.value.find(patient => patient.realName === value);
  if (selectedPatient) {
    form.value.patientId = selectedPatient.patientId; // 设置患者ID
    // 根据 patientId 查询住院记录
    listBeinhospital({ patientId: selectedPatient.patientId }).then(hospitalRecords => {
      if (hospitalRecords.rows.length > 0) {
        // 按住院日期排序，找到最新的住院记录
        const latestRecord = hospitalRecords.rows.sort((a, b) => new Date(b.admissionTime) - new Date(a.admissionTime))[0];
        form.value.nurseId = latestRecord.nurseId; // 将最新的住院记录中的护士 ID 赋值给当前记录的护士 ID
      }
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    nursingRecordId: null,
    nursingDateTime: null,
    nursingContent: null,
    vitals: null,
    patientConditionRecord: null,
    nurseId: null,
    patientName: null, // 替换为患者姓名
    registrationId: null,
    ext1: null,
    ext2: null,
    ext3: null,
    ext4: null
  };
  proxy.resetForm("nurserecordRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.nursingRecordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加患者住院护理记录";
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const _nursingRecordId = row.nursingRecordId || ids.value;
  getNurserecord(_nursingRecordId).then(response => {
    const patient = patientList.value.find(p => p.patientId === response.data.patientId);
    form.value = {
      ...response.data,
      patientName: patient ? patient.realName : "" // 设置患者姓名
    };
    open.value = true;
    title.value = "修改患者住院护理记录";
  });
}

// 提交按钮
function submitForm() {
  proxy.$refs["nurserecordRef"].validate(valid => {
    if (valid) {
      const selectedPatient = patientList.value.find(patient => patient.realName === form.value.patientName);
      if (selectedPatient) {
        form.value.patientId = selectedPatient.patientId; // 设置患者ID
      }
      if (form.value.nursingRecordId != null) {
        updateNurserecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addNurserecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const _nursingRecordIds = row.nursingRecordId || ids.value;
  proxy.$modal.confirm('是否确认删除患者住院护理记录编号为"' + _nursingRecordIds + '"的数据项？').then(function () {
    return delNurserecord(_nursingRecordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  proxy.download('nurse/nurserecord/export', {
    ...queryParams.value
  }, `nurserecord_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getPatientList();
});
</script>